package org.openkanban.client.ui.presenter;

import org.openkanban.client.ui.board.ActivityView;
import org.openkanban.client.ui.board.WhiteBoardView;
import org.openkanban.client.util.RootPanel;
import org.openkanban.shared.dto.ActivityDto;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.smartgwt.client.util.JSON;

/**
 * Callback that handles get activies request
 */
public class GetActivitiesByBoardIdRequestCallback implements RequestCallback {

    private WhiteBoardView whiteBoardView;

    public GetActivitiesByBoardIdRequestCallback(WhiteBoardView whiteBoardView) {
	this.whiteBoardView = whiteBoardView;
    }

    @Override
    public void onResponseReceived(Request request, Response response) {
	JSONArray jsa = new JSONArray(JSON.decode(response.getText()));

	RootPanel.main.getBoard().getWhiteBoardView().removeActivitiesHLayoutMembers();

	ActivityDto activityDto;
	if (jsa.size() > 0) {
	    RootPanel.main.getBoard().showNewKanbanButton();
	    for (int i = 0; i < jsa.size(); i++) {
		activityDto = new ActivityDto(jsa.get(i).isObject().toString());

		ActivityView newActivityView = new ActivityView(activityDto, whiteBoardView.getBoardDto().getBoardId());
		whiteBoardView.addActivity(newActivityView);
	    }
	} else {
	    RootPanel.main.getBoard().hideNewKanbanButton();
	}
    }

    @Override
    public void onError(Request request, Throwable exception) {

    }

}
